package cn.tonyandmoney.voicenotes.greendao.utils

import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.util.Log
import cn.tonyandmoney.voicenotes.App
import cn.tonyandmoney.voicenotes.greendao.gen.DaoMaster
import cn.tonyandmoney.voicenotes.greendao.gen.DaoSession

/**
 * Created by niantuo on 2017/9/23.
 * 数据库的辅助类
 */
class GreenDaoHelper {

    private val TAG: String = GreenDaoHelper::class.java.simpleName
    private lateinit var mHelper: SQLiteOpenHelper
    private var db: SQLiteDatabase? = null
    lateinit var mSession: DaoSession
    private var init = false


    fun init(context: Context) {
        synchronized(GreenDaoHelper::class) {
            if (init) return
            init = true
            mHelper = SQLiteOpenHelper(context, DB_NAME)
            if (db == null)
                db = mHelper.writableDatabase
            val mMaster = DaoMaster(db)
            mSession = mMaster.newSession()
            Log.d(TAG, "initGreenDao   over  ")
        }
    }


    companion object {
        const val DB_NAME = "Notes"
        val helper = GreenDaoHelper()

        fun session(): DaoSession {
            if (!helper.init) helper.init(App.app)
            return helper.mSession
        }
    }
}